<?php

namespace app\api\Logic;

use BsPaySdk\core\BsPayClient;
use BsPaySdk\request\V2TradePaymentJspayRequest;
use BsPaySdk\request\V2TradePaymentScanpayRefundRequest;
use think\Config;

class payLogic
{
    private $huifuid = "6666000175843373";

    public function __construct()
    {
        require_once ROOT_PATH . '/vendor/huifurepo/dg-php-sdk/BsPayLoader/loader.php';
    }

    private static $_instance;

    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 微信支付
     * @param $notifyUrl
     * @param $orderid
     * @param $money
     * @param $payType
     * @param $openid
     * @return array
     */
    public function createPay($notifyUrl, $orderid, $money, $payType = 'WXPAY', $openid = '1')
    {
        $return_res = ['code' => 0, 'msg', 'data' => null];

        require_once ROOT_PATH . "/vendor/huifurepo/dg-php-sdk/BsPaySdk/request/V2TradePaymentJspayRequest.php";

        $appid = 1;

        if ($payType == 'WXPAY') {
            $appid   = Config::get('xcx_appid');
            $payType = 'T_JSAPI';
        }
        $request = new V2TradePaymentJspayRequest();

        //请求日期
        $request->setReqDate(date("Ymd"));
        //请求流水号/订单号
        $request->setReqSeqId($orderid);
        //商户号
        $request->setHuifuId($this->huifuid);
        //商品描述
        $request->setGoodsDesc('订单支付');
        //交易类型
        $request->setTradeType($payType);  //微信小程序-T_MINIAPP
        //交易金额
        $request->setTransAmt(bcadd($money, 0, 2));

        //订单过期时间3天
        $orderTimeExpire = time() + 3 * 24 * 3600;

        //微信参数集合
        $wxDataArr = [
            "sub_appid"  => $appid, //子商户微信小程序ID
            "sub_openid" => $openid, // 子商户用户标识
        ];

        //设置非必填字段
        $extendInfoMap = [
            "time_expire"     => date('YmdHis', $orderTimeExpire),  //默认两小时关单
            "delay_acct_flag" => "Y",  //延时分账 Y: 延迟 N: 实时（默认）
            "remark"          => '订单支付', //订单备注
            "notify_url"      => $notifyUrl, //异步通知地址
            "wx_data"         => json_encode($wxDataArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //微信参数集合
        ];
        $request->setExtendInfo($extendInfoMap);

        //发起API调用
        $client = new BsPayClient();
        $result = $client->postRequest($request);
//        inventedPayLog('汇付测试',$result);
        if (!$result || $result->isError()) {  //失败处理
            $return_res['msg'] = '支付失败,原因' . $result->getErrorInfo();
            return $return_res;
        }

        //获取应答的数据
        $rspDatas = $result->getRspDatas();
        if (!isset($rspDatas["data"])) {
            $return_res['msg'] = '支付失败,返回值缺少data数据';
            return $return_res;
        }

        //进行判断结果
        $rspDatasArr = $rspDatas['data'];
        if (!isset($rspDatasArr["pay_info"])) {
            $return_res['msg'] = '支付失败,返回的结果:' . $rspDatasArr["resp_desc"];
            return $return_res;
        }

        $return_res['code'] = 1;
        $return_res['msg']  = '支付成功';
        $return_res['data'] = $rspDatas;
        return $return_res;
    }

    /**
     * 退款接口
     * @param array $params
     * @return array
     */
    public function refund(array $params = []): array
    {
        $notifyUrl    = trim($params['notifyUrl']) ?? '';           // 回调地址
        $amount       = floatval($params['amount']) ?? 0;           // 退款金额
        $org_req_date = trim($params['org_req_date']) ?? '';        // 原交易请求日期
        $org_order_sn = trim($params['org_order_sn']) ?? '';        // 原交易订单编号
        $order_sn     = 'T' . date('Ymd') . mt_rand(100000, 999999);// 订单编号
        $amount       = number_format($amount, 2, '.', '');

        $return_res = ['code' => 0, 'msg' => '', 'data' => null];

        require_once ROOT_PATH . "/vendor/huifurepo/dg-php-sdk/BsPaySdk/request/V2TradePaymentScanpayRefundRequest.php";

        // 2.组装请求参数
        $request = new V2TradePaymentScanpayRefundRequest();
        // 请求日期
        $request->setReqDate(date("Ymd"));
        // 请求流水号
        $request->setReqSeqId($order_sn);
        // 商户号
        $request->setHuifuId($this->huifuid);
        // 申请退款金额
        $request->setOrdAmt($amount);
        // 原交易请求日期
        $request->setOrgReqDate($org_req_date);

        // 设置非必填字段
        $extendInfoMap = [];
        // 原交易全局流水号
        $extendInfoMap["org_hf_seq_id"] = $org_order_sn;
        // 异步通知地址
        $extendInfoMap["notify_url"] = $notifyUrl;
        $request->setExtendInfo($extendInfoMap);

        // 3. 发起API调用
        $client = new BsPayClient();
        $result = $client->postRequest($request);
        if (!$result || $result->isError()) {  //失败处理
            $return_res['msg'] = '退款失败,原因' . $result->getErrorInfo();
            return $return_res;
        }

        //获取应答的数据
        $rspDatas = $result->getRspDatas();
        if (!isset($rspDatas["data"])) {
            $return_res['msg'] = '退款失败,返回值缺少data数据';
            return $return_res;
        }

        if (!in_array($rspDatas['data']['resp_code'], ['00000000', '00000100'])) {
            $return_res['msg'] = '退款失败,原因' . $rspDatas['data']['resp_desc'];
            return $return_res;
        }

        $return_res['code'] = 1;
        $return_res['msg']  = '退款成功';
        $return_res['data'] = $rspDatas;
        return $return_res;
    }
}